import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { Split, TitleLine, TextLine, TextCell } from '@components/ApprovePre/Approve'
import { defaultProcedure } from '@src/assets/js/config'

export default class SecretaryHistory extends Component {
  state = {
    varsMap: {}
  }

  // 初始化vars映射对象
  initVarsMap () {
    const varsMap = {}
    const vars = (this.props.action || {}).vars || []
    vars.forEach(li => {
      varsMap[li.key] = li.value
    })
    this.setState({ varsMap })
  }

  // 格式化日期
  formatDate (date) {
    if (date) {
      return moment(date * 1000).format('YYYY-MM-DD HH:mm')
    }
  }

  componentDidUpdate (prev) {
    if (prev.action !== this.props.action) {
      this.initVarsMap()
    }
  }

  componentDidMount () {
    this.initVarsMap()
  }

  // 渲染当事人的仲裁员选择情况
  renderPartySituation () {
    const currentid = this.props.userInfo.employeeid // 当前操作者id
    const operatorid = this.props.action.operatorid // 历史操作者id
    if (currentid === operatorid) {
      return this.renderParty()
    } else {
      return this.renderPublicParty()
    }
  }

  // 渲染仲裁员详情链接
  renderArbitratorLink (name, id) {
    if (typeof id === 'string' && id.length > 0) {
      return <a onClick={() => this.props.showArbitratorDetail(id)}>{name}</a>
    }
    return name
  }

  // 根据当事人类型显示选择情况
  renderPartyByType (type) {
    let list = []
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    if (type === '申请人') {
      list = JSON.parse((this.state.varsMap.claimants_arbitrators || '[]')) || []
    } else if (type === '被申请人') {
      list = JSON.parse((this.state.varsMap.respondents_arbitrators || '[]')) || []
    }
    return list.map((li, i) => {
      if (isNormal) {
        return (
          <TextLine key={i}>
            <TextCell>当事人：{li.party_name}</TextCell>
            <Split />
            <TextCell>首席仲裁员：{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</TextCell>
            <Split />
            <TextCell>仲裁员：{this.renderArbitratorLink(li.arbitrator1, li.arbitratorid1)}</TextCell>
          </TextLine>
        )
      }
      return (
        <TextLine key={i}>
          <TextCell>当事人：{li.party_name}</TextCell>
          <Split />
          <TextCell>仲裁员：{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</TextCell>
        </TextLine>
      )
    })
  }

  // 渲染当事人选择情况详情
  renderParty () {
    return (
      <div>
        <TitleLine title='申请人' />
        {this.renderPartyByType('申请人')}
        <TitleLine title='被申请人' />
        {this.renderPartyByType('被申请人')}
      </div>
    )
  }

  // 渲染简易程序当事人选择情况
  renderSimplePublicParty () {
    const { varsMap } = this.state
    const isSamePri = varsMap.arbitratorid_claimant && varsMap.arbitratorid_claimant === varsMap.arbitratorid_respondent // 当事人是否共同选定首席
    if (isSamePri) {
      return null
    }
    let claimants = []
    let respondents = []
    const nameStyle = { fontWeight: 'bold', margin: '0 4px' }
    if (varsMap.claimants_arbitrators) {
      try {
        claimants = JSON.parse(varsMap.claimants_arbitrators)
      } catch (e) {
        console.warn('解析申请人选择情况失败')
      }
    }
    if (varsMap.respondents_arbitrators) {
      try {
        respondents = JSON.parse(varsMap.respondents_arbitrators)
      } catch (e) {
        console.warn('解析被申请人选择情况失败')
      }
    }
    if (claimants.length === 0 && respondents.length === 0) {
      return null
    }
    claimants = claimants.filter(li => li.arbitratorid)
    respondents = respondents.filter(li => li.arbitratorid)
    return (
      <div>
        <TitleLine title='当事人选择情况' />
        <TextLine>
          <TextCell style={{ width: '100%' }}>
            {claimants.map((li, i) => <span key={i}>申请人<span style={nameStyle}>{li.party_name}</span>指定<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为仲裁员；</span>)}
            {respondents.map((li, i) => <span key={i}>被申请人<span style={nameStyle}>{li.party_name}</span>指定<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为仲裁员；</span>)}
            {claimants.length === 0 && respondents.length === 0 ? <span>无</span> : ''}
          </TextCell>
        </TextLine>
      </div>
    )
  }

  // 获取非简易程序当事人选择情况
  renderNormalPublicParty () {
    const { varsMap } = this.state
    const isSamePri = varsMap.arbitratorid_claimant && varsMap.arbitratorid_claimant === varsMap.arbitratorid_respondent // 当事人是否共同选定首席
    const isSameFrist = !!varsMap.arbitratorid1_claimant && varsMap.arbitrator1_claimant !== '未选定' // 申请人是否共同选择第一边裁
    const isSameSecond = !!varsMap.arbitratorid1_respondent && varsMap.arbitrator1_respondent !== '未选定' // 被申请人是否共同选择第二边裁
    const list = []
    let claimants = []
    let respondents = []
    const nameStyle = { fontWeight: 'bold', margin: '0 4px' }
    if (varsMap.claimants_arbitrators) {
      try {
        claimants = JSON.parse(varsMap.claimants_arbitrators)
      } catch (e) {
        console.warn('解析申请人选择情况失败')
      }
    }
    if (varsMap.respondents_arbitrators) {
      try {
        respondents = JSON.parse(varsMap.respondents_arbitrators)
      } catch (e) {
        console.warn('解析被申请人选择情况失败')
      }
    }
    if (isSamePri) {
      list.push(<span>当事人共同选定<span style={nameStyle}>{this.renderArbitratorLink(varsMap.arbitrator_claimant, varsMap.arbitratorid_claimant)}</span>为首席仲裁员；</span>)
      list.push(<br />)
    }
    if (isSameFrist) {
      list.push(<span>申请人共同选定<span style={nameStyle}>{this.renderArbitratorLink(varsMap.arbitrator1_claimant, varsMap.arbitratorid1_claimant)}</span>为第一边裁；</span>)
      list.push(<br />)
    }
    if (isSameSecond) {
      list.push(<span>被申请人共同选定<span style={nameStyle}>{this.renderArbitratorLink(varsMap.arbitrator1_respondent, varsMap.arbitratorid1_respondent)}</span>为第二边裁；</span>)
      list.push(<br />)
    }
    claimants.forEach(li => {
      const hasPri = !isSamePri && li.arbitratorid
      const hasOther = !isSameFrist && li.arbitratorid1
      if (hasPri && hasOther) {
        list.push((
          <span>
            <span>申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为首席仲裁员</span>
            <span>，并选择<span style={nameStyle}>{li.arbitrator1}</span>为第一边裁；</span>
          </span>
        ))
      } else if (hasPri) {
        list.push(<span>申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为首席仲裁员；</span>)
      } else if (hasOther) {
        list.push(<span>申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator1, li.arbitratorid1)}</span>为第一边裁；</span>)
      }
      if (hasPri || hasOther) {
        list.push(<br />)
      }
    })
    respondents.forEach(li => {
      const hasPri = !isSamePri && li.arbitratorid
      const hasOther = !isSameSecond && li.arbitratorid1
      if (hasPri && hasOther) {
        list.push((
          <span>
            <span>被申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为首席仲裁员</span>
            <span>，并选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator1, li.arbitratorid1)}</span>为第二边裁；</span>
          </span>
        ))
      } else if (hasPri) {
        list.push(<span>被申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator, li.arbitratorid)}</span>为首席仲裁员；</span>)
      } else if (hasOther) {
        list.push(<span>被申请人<span style={nameStyle}>{li.party_name}</span>选择<span style={nameStyle}>{this.renderArbitratorLink(li.arbitrator1, li.arbitratorid1)}</span>为第二边裁；</span>)
      }
      if (hasPri || hasOther) {
        list.push(<br />)
      }
    })
    return list
  }

  // 渲染公开当事人选择情况
  renderPublicParty () {
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    if (!isNormal) {
      return this.renderSimplePublicParty()
    }
    const list = this.renderNormalPublicParty()
    if (list.length === 0) { return null }
    return (
      <div>
        <TitleLine title='当事人选择情况' />
        <TextLine>
          <TextCell style={{ width: '100%' }}>
            {list.map((li, i) => <span key={i}>{li}</span>)}
          </TextCell>
        </TextLine>
      </div>
    )
  }

  renderNormal (c) {
    const { caseDetail } = this.props
    if (caseDetail.procedure === defaultProcedure) {
      const { varsMap } = this.state
      const isSameFrist = !!varsMap.arbitrator1_recommend1 && !['委托主任指定', '未选定'].includes(varsMap.arbitrator1_recommend1) && varsMap.arbitrator1_recommend1 === c.arbitrator1_claimant
      const isSameSecond = !!varsMap.arbitrator2_recommend1 && !['委托主任指定', '未选定'].includes(varsMap.arbitrator2_recommend1) && varsMap.arbitrator2_recommend1 === c.arbitrator1_respondent
      return (
        <>
          <Split />
          <TextCell>仲裁员：{(isSameFrist ? '无推荐' : this.renderArbitratorLink(varsMap.arbitrator1_recommend1, varsMap.arbitratorid1_recommend1)) || '无推荐'}</TextCell>
          <Split />
          <TextCell>仲裁员：{(isSameSecond ? '无推荐' : this.renderArbitratorLink(varsMap.arbitrator2_recommend1, varsMap.arbitratorid2_recommend1)) || '无推荐'}</TextCell>
        </>
      )
    }
  }

  render () {
    const { action, instance } = this.props
    const c = instance.formCourt
    return (
      <div>
        <TitleLine title={this.props.action.step_name} operator={action.operator} time={this.formatDate(action.complete_datetime)} />
        <TextLine>
          <TextCell>组庭类型：{c.type}</TextCell>
          <Split />
          <TextCell style={{ width: '65%' }}>{action.remark_alias || '备注'}：{action.remark || '无'}</TextCell>
        </TextLine>
        {this.renderPartySituation()}
        {this.props.renderDocument()}
      </div>
    )
  }
}

SecretaryHistory.proptypes = {
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  action: PropTypes.object,
  caseDetail: PropTypes.object,
  renderDocument: PropTypes.func,
  showArbitratorDetail: PropTypes.func
}

SecretaryHistory.defaultProps = {
  userInfo: {},
  instance: {},
  action: {},
  caseDetail: {},
  renderDocument: () => {},
  showArbitratorDetail: () => {}
}
